/**
 * 时间工厂
 */
class DateFactory {
  constructor() {
    this._date = new Date();
    this._year = this._date.getFullYear();
    this._month = this._date.getMonth() + 1;
    this._day = this._date.getDate();
    this._hours = this._date.getHours();
    this._minutes = this._date.getMinutes();
    this._dayTag = this._date.getDay();
  }
  /**
   * 初始化
   */
  init() {
    this._todayTimeArr = [];
    this._defaultTimeArr = [];
    this._timeArr = [];
    this._weekArr = [];
    this._hourArr = [];

    this.createTodayTimeArr(this._todayTimeArr, this._hours, this._minutes);
    this.createDefaultTimeArr(this._defaultTimeArr);

    let i, tempDayTag = this._dayTag, _this = this;
    for (i = 0; i < 14; i++) {
      if (i > 0) {
        ++tempDayTag;
      }
      if (tempDayTag > 13) {
        tempDayTag = 0;
      }
      this._weekArr.push({
        id: i,
        name: this.switchWeek(tempDayTag)
      });
      // this._hourArr.push({
      //   id: i,
      //   hourArr: i == 0 ? this._todayTimeArr : this._defaultTimeArr
      // })
    }
    // this._timeArr[1] = this._hourArr[0];
  }

  /**
   * 根据时间创建当天数组
   */
  createTodayTimeArr(todayTimeArr, currHours, minutes) {
    if (todayTimeArr) {
      let i;
      for (i = currHours; i < 24; i++) {
        if (i == currHours) {
          if (minutes < 30) {
            todayTimeArr.push({
              name: i + ":30"
            });
          }
        } else {
          todayTimeArr.push({
            name: i + ":00"
          });
          todayTimeArr.push({
            name: i + ":30"
          });
        }
      }
    }
  }


  /**
   * 其他时间数组生产
   */
  createDefaultTimeArr(defaultTimeArr) {
    if (defaultTimeArr) {
      let i;
      for (i = 0; i < 24; i++) {
        defaultTimeArr.push({
          name: i + ":00"
        });
        defaultTimeArr.push({
          name: i + ":30"
        });
      }
    }
  }


  /**
   * 选择日期
   * @param dayTag 当天时间标记戳
   * @return int 不存在返回-1，否则返回其对应的中文名称
   */
  switchWeek(dayTag) {
    let currentDayTag = dayTag > 6 ? dayTag - 7 : dayTag;
    switch (currentDayTag) {
      case 0:
        return "星期天"
        break;
      case 1:
        return "星期一"
        break;
      case 2:
        return "星期二"
        break;
      case 3:
        return "星期三"
        break;
      case 4:
        return "星期四"
        break;
      case 5:
        return "星期五"
        break;
      case 6:
        return "星期六"
        break;
    }
    return -1;
  }
}

const dateFactory = new DateFactory()
dateFactory.init();

var api = require("../../../../api.js"),
  QQMapWX = require("../../../../qqmap-wx.js"),
  app = getApp();
Page({
  data: {
    status:0,
    timeArr: null,
    cid: '',
    rewardArr: [
      {
        price: 0,
        text: '0元'
      },
      {
        price: 1,
        text: '1元'
      },
      {
        price: 2,
        text: '2元'
      },
      {
        price: 3,
        text: '3元'
      },
      {
        price: 4,
        text: '4元'
      },
      {
        price: 5,
        text: '6元'
      },
      {
        price: 10,
        text: '10元'
      },
      {
        price: 15,
        text: '15元'
      },
      {
        price: 20,
        text: '20元'
      }
    ],
    couponArr: [
      {
        price: 0,
        text: ''
      },
    ],
    stepper: {
      stepper: 0
    },
    huiyuan:'',
    full_money: '',
    time: '', // 时间字符串
    price: 0, // 跑腿费
    paiduiprice:0,//排队费
    reward: 0,  // 小费
    coupon: 0,  // 优惠券红包
    lastPrice: 0, // 最终价格
    detail_info: '',
    addressId: '',  // 数据库地址id
    clickpay:true,
    wareText: '', // 商品名称字符串
    didianprice: 0,
    timeprice: 0,
    inputAddressText: '', // 输入的收货地址
    isReadProtocol: true,  // 是否阅读协议
    selectionService:0,
    proxy_id:0,
    service:[
      {
        tid: 1,
        sname: "仅排队"
      },
      {
        tid: 2,
        sname: "取物件"
      },
      {
        tid: 3,
        sname: "取送物件"
      }
    ],
    isBargaining: false,  // 是否议价
    isOpenPreference: false, // 是否开启会员优惠 
    isOpenIntegralDeduction: false,  // 是否开启积分抵扣
    integral:'',
    show: false,
    cancelWithMask: true,
    actions: [{
      name: '微信支付',
      subname: '使用微信官方支付方式',
      className: 'action-class',
      loading: false
    }, {
      name: '余额支付',
      subname: '使用平台账户余额支付',
      className: 'action-class',
      loading: false
    }],
    cancelText: '取消'
  },

  couponurl: function () {
    var that = this;
    app.request({
      url: api.Coupon.coupon,
      data: {
        uid: wx.getStorageSync('uid')
      },
      success: function (e) {
        that.setData({
          couponArr: e.data
        })
      }
    })
  },
  onLoad: function (option) {
    let _this = this;
    app.request({
      method: 'POST',
      url: api.default.orderGetPageConfig,
      data: {
        bid: wx.getStorageSync('bid')
      },
      success: function (data) {

        let status = data.status;
        let pageConfig = JSON.parse(data.diy);
        if (status) {
          // 设置标题
          wx.setNavigationBarTitle({
            title: pageConfig.titleConfig.pageTitle
          })
          // 设置颜色
          wx.setNavigationBarColor({
            frontColor: pageConfig.titleConfig.fontColor.toLocaleLowerCase(),
            backgroundColor: pageConfig.titleConfig.navigationBgColor,
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          })

          // 设置数据
          _this.setData({
            pageConfig: pageConfig
          });
        }
      }
    });
    
    var that = this;
    that.setData({
      icons: wx.getStorageSync('site') + '/addons/sd_liferuning/tp/public/uploads/background',
    })
    if(wx.getStorageSync('huiyuan')=="非会员用户"){
      that.setData({
        huiyuan:1
      })
    }
    
    // that.setData({
    //   cid: option.cid,
    // });

    // if (wx.getStorageSync('phone') == '') {
    //   wx.redirectTo({
    //     url: '/sd_liferuning/pages/login/login',
    //   })
    // }
    if (option.addressId) {
      that.setData({
        time: option.time,
        price: option.price,
        reward: option.reward,
        coupon: option.coupon,
        lastPrice: option.lastPrice,
        addressId: option.addressId,
        inputAddressText: option.inputAddressText,
        wareText: option.wareText,
        cid: option.cid,
      });
    } else {
      that.setData({
        wareText: option.wareText ? option.wareText:'',
      });
    }
    /**
    * 时间选择
    */
    let timeArr = [];
    app.request({
      url: api.default.timelist,
      data: {
        time: 0
      },
      success: function (res) {
        timeArr[0] = dateFactory._weekArr;
        timeArr[1] = res.data;
        timeArr[2] = res.data;
        _this.setData({
          timeArr: timeArr
        })
      }
    })
    var id = option.id;
    /** 获去服务名称 和 快捷标签 */
    app.request({
      url: api.default.classBq,
      data: {
        bid: wx.getStorageSync('bid'),
        id: id
      },
      success: function (res) {
        console.log('服务',res)
        if (res.data == '') {
          wx.navigateTo({
            url: '/sd_liferuning/pages/constmer/index/index',
          })
        } else {
          if (res.data.three != []){
            that.setData({
              service: res.data.three,
            })
          }else{
            that.setData({
              service: res.data.three,
              wareText:res.data.three[0].sname,
              cid: res.data.three[0].tid
            })
          }
          if (res.data.biaoqian != '') {
            that.setData({
              wareText: res.data.name,
              biaoqian: res.data.biaoqian
            })
          } else {
            that.setData({
              wareText: res.data.name,
              biaoqian: []
            })
          }
        }
      }
    })
  },
  onShow: function (option) {
    /**默认地址 */
    var that = this
    that.couponurl();
    app.request({
      url: api.default.mrAddress,
      data: {
        bid: wx.getStorageSync('bid'),
        uid: wx.getStorageSync('uid')
      },
      success: function (res) {
        //console.log('地址', res);
        console.log(res.data.phone)
        if (res.data.adress == '') {
          wx.showToast({
            title: '请添加收货地址',
            icon: 'succes',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                wx.navigateTo({
                  url: '/sd_liferuning/pages/constmer/address-list/index',
                })
              }, 2000)
            }
          })   
        } else {
          
          that.setData({
            detail_info: res.data.adress,
            username: res.data.name,
            phone: res.data.phone,
            uaid: res.data.uaid
          })
        }
      }
    })
    /***保险 */
    app.request({
      url: api.default.Insprice,
      data: {
        bid: wx.getStorageSync('bid'),
      },
      success: function (res) {
        var ins = ''
        if (res.data.insprice != undefined) {
          that.setData({
            ins: res.data.insprice
          })
          that.countPrice();
        } else {
          that.setData({
            ins: 0.00
          })
          that.countPrice();
        }
      }
    })
  },
  /**
   * 选择位置
   */
  GetAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        that.setData({
          hasLocation: true,
          location: {
            longitude: res.longitude,   //经度
            latitude: res.latitude     //纬度
          },
          detail_infos: res.address,   //详细地址
          wd: res.latitude,
          jd: res.longitude
        })
      },
      complete(data) {
        if (that.data.detail_info != '' && that.data.wd != undefined && that.data.jd != undefined && that.data.detail_infos != '' && that.data.wd != '' && that.data.jd != '') {
          var wd = that.data.wd
          var jd = that.data.jd
          // console.log(that.data.jd);
          /**解析地址*/
          var demo = new QQMapWX({
            key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
          });
          // var that = this
          demo.geocoder({
            address: that.data.detail_info,
            success: function (res) {
              // console.log('我的地址',res.result.location);
              // console.log('目的地', wd);
              /** 两个地址不为空请求金额 */
              app.request({
                url: api.default.addprice,
                metho: 'post',
                data: {
                  myaddsjd: res.result.location['lng'],
                  myaddswd: res.result.location['lat'],
                  mudaddswd: wd,
                  mudaddsjd: jd,
                  bid: wx.getStorageSync('bid')
                },
                success: function (res) {
                  var scq = that.data.didianprice
                  //console.log(scq);
                  //console.log('金额', res)
                  console.log('区域代理',res)
                  if (that.data.status!=0){
                    that.setData({
                      didianprice: res.data,
                      price: that.data.price - scq + res.data,
                    })
                    that.countPrice();
                  }
                  if (res.data.region_id) that.setData({ proxy_id: res.data.proxy_id ? res.data.proxy_id : 0})
                }

              })
            },
          });
        }
      }
    })
  },
  pickerSelector: function (e) {
    var that = this;
    var pickerType = e.currentTarget.dataset.type;
    var val = e.detail.value;
    if (pickerType == 'time') {
      if (that.data.timeArr[1][val[1]].timechuo >= that.data.timeArr[2][val[2]].timechuo){
        wx.showToast({
          icon: 'none',
          title: '请至少间隔半个小时的排队时间',
        })
        return false;
      }
      that.setData({
        time: {
          week: that.data.timeArr[0][val[0]],
          firstHour: that.data.timeArr[1][val[1]],
          lastHour: that.data.timeArr[2][val[2]]
        }
      });
      /*** 时间金额*/
      var that = this
      console.log(that.data.time)
      app.request({
        url: api.default.time_price,
        data: {
          wid: that.data.timeArr[0][val[0]]['name'],
          hid: that.data.timeArr[1][val[1]]['name']
        },
        success: function (data) {
          var timeprice = that.data.timeprice
          console.log(data)
          that.setData({     //显示配送时间费用
            timeprice: (that.data.time.lastHour.timechuo - that.data.time.firstHour.timechuo) / 60 * 0.6,
            paiduiprice: (that.data.time.lastHour.timechuo - that.data.time.firstHour.timechuo) / 60 * 0.6
          })
          that.countPrice();
        }
      })
    }
    if (pickerType == 'reward') {
      that.setData({
        reward: that.data.rewardArr[val].price
      });
    }
    if (pickerType == 'coupon') {
      if (that.data.couponArr.length !=0){
        that.setData({
          coupon: that.data.couponArr[val].price,
          full_money: that.data.couponArr[val].full_money,
          useid: that.data.couponArr[val].id
        });
        if (that.data.lastPrice < that.data.full_money) {
          wx.showToast({
            title: '未达到使用要求',
          })
        } 
         
      }
    }
    that.countPrice();
  },
  bindColumnChange: function (e) {
    var _this = this;
    var timeArr = _this.data.timeArr;
    var column = e.detail.column;
    var columnVal = e.detail.value;
    /**
    * 时间选择
    */
    if (column == 0) {
      app.request({
        url: api.default.timelist,
        data: {
          time: columnVal
        },
        success: function (res) {
          timeArr[1] = res.data;
          timeArr[2] = res.data;
          _this.setData({
            timeArr: timeArr
          })
        }
      })
    }
  },
  countPrice: function () {
    var that = this;
    var money = Number(that.data.price) + Number(that.data.timeprice) + Number(that.data.stepper.stepper) + Number(that.data.ins) + Number(that.data.reward) - Number(that.data.integral);

    if (money < that.data.full_money) {
      money = Number(that.data.price) + Number(that.data.timeprice) + Number(that.data.stepper.stepper) + Number(that.data.ins) + Number(that.data.reward) - Number(that.data.integral);
      that.setData({
        coupon: 0
      })
    } else {
      money = Number(that.data.price) + Number(that.data.timeprice) + Number(that.data.stepper.stepper) + Number(that.data.ins) + Number(that.data.reward) - Number(that.data.coupon) - Number(that.data.integral);
    }
    if (money < 0.01) {
      money = 0.00
    }
    that.setData({
      lastPrice: money.toFixed(2)
    });
  },
  changeInputData: function (e) {
    // console.log('地址',11)
    // return false;
    var that = this;
    var inputName = e.currentTarget.dataset.name;
    var inputVlaue = e.detail.value;
    if (inputName == "wareText") {
      that.setData({
        wareText: inputVlaue
      });
    }
    if (inputName == "inputAddressText") {
      that.setData({
        inputAddressText: inputVlaue
      });
    }
  },
  /**提交订单*/
  formSubmit: function (e) {
    var _this = this;
    if (e.detail.value.goodsname != '' && e.detail.value.mytimes != 'NaN' && _this.data.isReadProtocol === true) {
      _this.setData({
        formData: e.detail.value,
        formId: e.detail.formId
      });
      _this.openActionsheet();
    } else {
      wx.showToast({
        title: '信息不完善，无法下单。',
      })
    }
  },
  /**
   * 添加商品
   */
  addWareItem: function (e) {
    let _this = this;
    let tag = e.currentTarget.dataset.tag;
    let wareText = _this.data.wareText;
    _this.setData({
      wareText: wareText + ", " + tag
    });
    //console.log(tag);
  },
  /**
   * 是否阅读协议
   */
  isRead: function (e) {
    let isReadProtocol = this.data.isReadProtocol;
    this.setData({
      isReadProtocol: !isReadProtocol
    });
  },
  /**
   * radio
   */
  radioChanged: function (e) {
    let val = e.detail.value;
    let name = e.currentTarget.dataset.name;
    if (name == "bargaining") {  // 根据name进行判断属于哪个radio
      this.setData({
        bargaining: val
      });
    }
  },
  selectionService: function(e){
    let _index = e.currentTarget.dataset.index;
    console.log(e)
    this.setData({
      selectionService: _index,
      wareText: this.data.pageConfig.mainConfig.templet3.serviceConfig.serviceGroups[_index].name
    });
  },

  // 开启选择器
  openActionsheet() {
    this.setData({
      'show': true
    });
  },
  // 关闭选择器
  closeActionSheet() {
    this.setData({
      'show': false
    });
  },
  // 根据选择进行调用事件
  clickAction({ detail }) {
    const { index } = detail;
    this.setData({
      [`actions[${index}].loading`]: true,
      actionType: index,
      clickpay: false
    });
    switch (index) {
      case 0: // 0 微信支付
        this.wechatPay();
        break;
      case 1: // 1 余额支付
        this.balancePay();
        break;
    }
    setTimeout(() => {
      this.setData({
        [`show`]: false,
        [`actions[${index}].loading`]: false
      });
    }, 100);
  },
  /**
   * 微信支付
   */
  wechatPay: function () {
    let _this = this;
    let _formData = _this.data.formData;  // 表单数据
    console.log("表单数据=>", _formData);
    console.log("微信支付");
    app.request({
      url: api.default.insertorder,
      data: {
        distype: _formData.distype,
        goodsname: _formData.goodsname,
        mudadds: _formData.mudadds + _formData.mudaddsinfors,
        myadds: _formData.myadds,
        xphoto: 0,
        yinpin: 0,
        times: _formData.mytimes,
        price: _formData.price,
        uid: wx.getStorageSync('uid'),
        redbao: _formData.redbao,
        tip: _formData.tip,
        bid: wx.getStorageSync('bid'),
        ins: _formData.ins,
        message: _formData.message,
        type: '排队',
        username: _this.data.username,
        phone: _this.data.phone,
        proxy_id: _this.data.proxy_id ? _this.data.proxy_id:0,
        imgurl:'',
      },
      success: function (res) {
        if (res.data) {
          /**获取支付参数 */
          app.request({
            url: api.default.orderpay,
            data: {
              order_no: res.data,
              title: '超人跑腿支付',
              uid: wx.getStorageSync('uid')
            },
            success: function (data) {
              _this.setData({
                clickpay: true
              })
              //console.log('支付参数', data.data.weixin)
              wx.requestPayment(
                {
                  'timeStamp': data.data.weixin.timeStamp,
                  'nonceStr': data.data.weixin.nonceStr,
                  'package': data.data.weixin.package,
                  'signType': 'MD5',
                  'paySign': data.data.weixin.paySign,
                  'success': function (res) {
                    //console.log('支付成功', res)
                    if (_this.data.useid) {
                      app.request({
                        url: api.Coupon.status,
                        data: {
                          useid: _this.data.useid
                        },
                        success: function (e) {
                          //console.log(e);
                        }
                      })
                    }
                    app.request({
                      url: api.user.mess,
                      data: {
                        bid: wx.getStorageSync('bid'),
                        openid: wx.getStorageSync('openid'),
                        order_no: data.data.weixin.order_no,
                        type: 'apply'
                      },
                      success: function (ddd) {
                        //console.log(ddd);
                      }
                    })
                    wx.redirectTo({
                      url: '/sd_liferuning/pages/constmer/order-list/index',
                    })
                  },
                  'complete': function (res) {
                    _this.setData({
                      clickpay: true
                    })
                  }
                })
            }
          })
        }
      }
    })
  },
  /**
   * 余额支付
   */
  balancePay: function () {
    let _this = this;
    let _formData = _this.data.formData;  // 表单数据
    let _formId = _this.data.formId;
    console.log("表单数据=>", _formData);
    app.request({
      url: api.default.insertorder,
      data: {
        distype: _formData.distype,
        goodsname: _formData.goodsname,
        mudadds: _formData.mudadds + _formData.mudaddsinfors,
        myadds: _formData.myadds,
        times: _formData.mytimes,
        price: _formData.price,
        xphoto: 0,
        yinpin: 0,
        imgurl: '',
        uid: wx.getStorageSync('uid'),
        redbao: _formData.redbao,
        tip: _formData.tip,
        bid: wx.getStorageSync('bid'),
        ins: _formData.ins,
        message: _formData.message,
        'type': '排队',
        username: _this.data.username,
        phone: _this.data.phone,
        proxy_id: _this.data.proxy_id ? _this.data.proxy_id : 0
      },
      success: function (e) {
        _this.setData({
          clickpay: true
        })
        if (e.code == 1) {
          app.request({
            url: api.order.pricePay,
            method: 'post',
            data: {
              uid: wx.getStorageSync('uid'),
              order_no: e.data,
              openid: wx.getStorageSync('openid'),
              formId: _formId,
            },
            success: function (e) {
              if (e.code == 1) {
                if (_this.data.useid) {
                  app.request({
                    url: api.Coupon.status,
                    data: {
                      useid: _this.data.useid
                    },
                    success: function (e) {
                      console.log(e);
                    }
                  })}
                wx.showToast({
                  title: e.msg,
                  duration: 1000,
                  success: function () {
                    setTimeout(function () {
                      wx.redirectTo({
                        url: '/sd_liferuning/pages/constmer/order-list/index',
                      })
                    }, 1000)
                  }
                })
              } else {
                wx.showToast({
                  title: e.msg,
                })
              }
            }
          })
        }
      }
    })

    console.log("余额支付");
  },
  /**
   * 小费
   */
  handleStepperChange: function ({
    detail: stepper,
    target: {
      dataset: {
        componentId
      }
    }
  }) {
    this.setData({
      [`${componentId}.stepper`]: stepper
    });
    this.countPrice();
  },
  /**
   * 是否议价
   */
  isBargaining: function (e) {
    let isBargaining = this.data.isBargaining;
    this.setData({
      isBargaining: !isBargaining
    });
  },
  isOpenPreference: function () {
    var that=this;
    let isOpenPreference = this.data.isOpenPreference;
    if (isOpenPreference == false) {
      wx.request({
        url: api.member.rebate,
        data: {
          uid: wx.getStorageSync('uid'),
          bid: wx.getStorageSync('bid')
        },
        method: 'get',
        success: function (res) {
          that.setData({
            vipprice: res.data.data.zhekou
          })
        }
      })
    } else {
      that.setData({
        vipprice: 0
      })
    }
    this.setData({
      isOpenPreference: !isOpenPreference
    });
  },
  /**
   * 积分抵扣
   */
  isOpenIntegralDeduction: function () {
    var that = this;
    let isOpenIntegralDeduction = this.data.isOpenIntegralDeduction;
    if (isOpenIntegralDeduction == false) {
      wx.request({
        url: api.member.integral,
        data: {
          uid: wx.getStorageSync('uid'),
          bid: wx.getStorageSync('bid')
        },
        method: 'post',
        success: function (res) {
          that.setData({
            integral: res.data.data.integral
          })
        }
      })
    } else {
      that.setData({
        integral: 0
      })
    }
    this.setData({
      isOpenIntegralDeduction: !isOpenIntegralDeduction
    });
  }
})